package com.bestplus.daqingapp.common.step;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

import com.bestplus.daqingapp.BuildConfig;
import com.bestplus.daqingapp.common.util.DataUtil;


public class Pedometer extends Service implements SensorEventListener {

	private static final int GRAY_NOTIFY_ID = 1928;

	private volatile static Pedometer self;

	private SensorManager mSensorManager;
//	private float mCounter;//步行总数
//	private float mDetector;//步行探测器
	private static int STEP_COUNTER;
	private static int STEP_DETECTOR;

	private StepCount mStepCount;

	public static Pedometer getSelf() {
		return self;
	}

	public static void start(Context context) {
		if (self == null)
			context.startService(new Intent(context, Pedometer.class));
	}


	@Nullable
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		self = this;
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mStepCount = new StepCount();
		mStepCount.setSteps(DataUtil.readFloat(this, StepCount.STEP_TODAY));
		PackageManager pm = getPackageManager();
		if (pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_DETECTOR)) {
			if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
				STEP_COUNTER = Sensor.TYPE_STEP_COUNTER;
				STEP_DETECTOR = Sensor.TYPE_STEP_DETECTOR;
				registerDetector();
			} else {
				registerAccelerator();
			}
		} else {
			registerAccelerator();
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
			//API < 18，此方法能有效隐藏Notification上的图标
			startForeground(GRAY_NOTIFY_ID, new Notification());
		} else {
			startForeground(GRAY_NOTIFY_ID, new Notification());
			Intent innerIntent = new Intent(this, InnerService.class);
			startService(innerIntent);
		}
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregister();
	}

	// @Override
	// public void onTaskRemoved(final Intent rootIntent) {
	// 	super.onTaskRemoved(rootIntent);
	// 	if (BuildConfig.DEBUG)
	// 		Log.i("log", "onTaskRemoved: Pedometer service task removed");
	// 	// Restart service
	// 	((AlarmManager) getSystemService(Context.ALARM_SERVICE))
	// 			.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
	// 					SystemClock.elapsedRealtime() + 1000,
	// 					PendingIntent.getService(this, 3, new Intent(this, Pedometer.class), 0));
	// }

	/**
	 * 通过计步传感器来计步
	 */
	public void registerDetector(){
//		Sensor mStepCounter = mSensorManager.getDefaultSensor(STEP_COUNTER);
		Sensor mStepDetector = mSensorManager.getDefaultSensor(STEP_DETECTOR);
//		register(mStepCounter, SensorManager.SENSOR_DELAY_FASTEST);
		register(mStepDetector, SensorManager.SENSOR_DELAY_FASTEST);
	}

	/**
	 * 通过加速度传感器来记步
	 */
	private void registerAccelerator() {
		// 获得传感器的类型，这里获得的类型是加速度传感器
		// 此方法用来注册，只有注册过才会生效，参数：SensorEventListener的实例，Sensor的实例，更新速率
		Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		boolean isAvailable = register(sensor, SensorManager.SENSOR_DELAY_FASTEST);
		if (BuildConfig.DEBUG)
			Log.i("log", "加速度传感器: " + isAvailable);
	}

	public void unregister(){
		mSensorManager.unregisterListener(this);
	}

	private boolean register(Sensor sensor, int rateUs) {
		return mSensorManager.registerListener(this, sensor, rateUs);
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == STEP_COUNTER) {
			if (BuildConfig.DEBUG)
				Log.i("log", "step counter: " + event.values[0]);
		}
		if (event.sensor.getType() == STEP_DETECTOR) {
			if (event.values[0] == 1.0F) {
				mStepCount.countStep();
			}
		}
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			mStepCount.getStepDetector().onSensorChanged(event);
		}
	}

//	public float getStepCount() {
//		return mCounter;
//	}

	public float getStepDetector() {
		return mStepCount.getSteps();
	}

	public float getStepDetector(int day) {
		return mStepCount.getSteps(day);
	}


   public float getStepDetector(int serverStep,String serverDay) {
		return mStepCount.getSteps(serverStep,serverDay);
	}

   public String getTime() {
		return mStepCount.getTime();
	}

	/**
	 * API >= 18 的系统上用的灰色保活Service
	 */
	public static class InnerService extends Service {

		@Nullable
		@Override
		public IBinder onBind(Intent intent) {
			return null;
		}

		@Override
		public int onStartCommand(Intent intent, int flags, int startId) {
			startForeground(GRAY_NOTIFY_ID, new Notification());
			stopSelf();
			return super.onStartCommand(intent, flags, startId);
		}

	}



}
